//
//  UploadViewController.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-5-17.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "UploadViewController.h"

#import "ViewControllerChooser.h"

#import "ItemEditViewController.h"

#import "UploadItem.h"

#import "DataManager.h"


@implementation UploadViewController

@synthesize table;

@synthesize uploading;

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/


- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	self.navigationItem.title = [NSString stringWithString:(NSLocalizedStringFromTable(@"UPLOAD_PHOTOS",@"main",@""))];
	picTitle = [NSString stringWithString:(NSLocalizedStringFromTable(@"IMAGE",@"main",@""))];
	if(imgs == nil){
		imgs = [[NSMutableArray alloc] init];
		picNumber = 1;
	}
}
/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	if(imgs != nil){
		[imgs removeAllObjects];
	}
}

-(void)reloadImages{
	[self.table reloadData];
}


#pragma mark -
#pragma mark UINavigationControllerDelegate

-(void)navigationController:(UINavigationController *)navigationController
	  didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
	// TODO 不需要
}

-(void)navigationController:(UINavigationController *)navigationController
	 willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
	// TODO 不需要
}



// UIImagePickerControllerDelegate 实现

// 对于3.0实现，需要使用另外的 方法

#ifndef __IPHONE_3_0
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
	UploadItem *uitem = [[UploadItem alloc] init];
	uitem.image = image;
	// 每次添加都变化
	uitem.title = [NSString stringWithFormat:@"%@ %d",picTitle,picNumber];
	// 采取加1操作
	picNumber++;
	[imgs addObject:uitem];
	[picker dismissModalViewControllerAnimated:NO];
	
	// TODO 刷新数据表格
	[self.table reloadData];
	// TODO 检查是否释放成功
	[uitem release];
}
#else
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
	UploadItem *uitem = [[UploadItem alloc] init];
	uitem.image = image;
	// 每次添加都变化
	uitem.title = [NSString stringWithFormat:@"%@ %d",picTitle,picNumber];
	// 采取加1操作
	picNumber++;
	[imgs addObject:uitem];
	[picker dismissModalViewControllerAnimated:NO];
	
	// TODO 刷新数据表格
	[self.table reloadData];
	
	[uitem release];
}
#endif

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
	[picker dismissModalViewControllerAnimated:NO];
}


-(IBAction)takePhoto:(id)sender{
	// TODO 从图片库获取
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
		if(pickerController == nil){
			pickerController = [[UIImagePickerController alloc] init];
		}
		pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
		pickerController.delegate = self;
		
		[self.navigationController presentModalViewController:pickerController animated:NO];
	}
}

-(IBAction)takeCamera:(id)sender{
	// TODO 从照相机获取
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
		if(pickerController == nil){
			pickerController = [[UIImagePickerController alloc] init];
		}
		pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
		pickerController.delegate = self;
		
		[self.navigationController presentModalViewController:pickerController animated:NO];
	}
}

#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	if(buttonIndex == 0){
		// TODO Index 0
	}else if(buttonIndex == 1){
		// TODO Index 1 经过测试，当对话框有两个按钮，一个是 Cancel 另一个是别的的时候 证明 Cancel == 0 其余的累加
		UIViewController *authView = [[ViewControllerChooser sharedChooser] choose:VCC_ID_AUTH];
		[self.navigationController pushViewController:authView animated:YES];
	}
}

/**
 * 提交数据，十分重要
 */
-(IBAction)sendPhotos:(id)sender{
	if(!isUploading){
		
		// TODO 检查用户是否已经通过授权了
		
		DataManager *dm = [DataManager sharedDataManager];
		if(![dm isAuthorized]){
			// TODO 提示用户，需要进行授权
			NSString *alTitle = [NSString stringWithString:(NSLocalizedStringFromTable(@"ERROR",@"main",@""))];
			NSString *alMessage = [NSString stringWithString:(NSLocalizedStringFromTable(@"NEED_AUTH",@"main",@""))];
			NSString *authTitle = [NSString stringWithString:(NSLocalizedStringFromTable(@"AUTH",@"main",@""))];
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alTitle message:alMessage delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:authTitle,nil];
			[alert show];
			[alert release];
		}else{
		
			// TODO 需要实现数据提交, 暂时实现直接上传，不进行界面显示
			if(imgs != nil){
				NSInteger con = [imgs count];
				if(con > 0){			
					UIBarButtonItem *bitem = [[UIBarButtonItem alloc] initWithCustomView:self.uploading];
					[self.navigationItem setRightBarButtonItem:bitem];
					[self.uploading startAnimating];
					// TODO 此处的设置，必须在线程启动之前，避免多嫌程造成混乱
					isUploading = YES;
					[NSThread detachNewThreadSelector:@selector(uploadImpl:) toTarget:self withObject:nil];
					[bitem release];
				}
			}
		}
	}
}

/**
 * 图像上传，实际的方法
 */
-(void)uploadImpl:(id)notification{
	
	NSInteger con = [imgs count];
	UploadItem *img;
	DataManager *dm = [DataManager sharedDataManager];
	BOOL bOK;
	for(int i = 0;i<con;i++){
		img = (UploadItem *)[imgs objectAtIndex:i];
		if(img.uploadState == US_NEEDUPLOAD){
			bOK = [dm uploadImageToServer:[img getImageData] withParams:[img getItemInfo]];
			if(bOK){
				img.uploadState = US_UPLOADED;
			}else{
				img.uploadState = US_ERROR;
				// 如果出现错误，那么就不要继续循环了，直接提示出错
				break;
			}
		}
		if(i % 2 == 0){
			[self.table reloadData];
		}
	}
	[self.uploading stopAnimating];
	[self.uploading removeFromSuperview];
	isUploading = NO;
	self.navigationItem.rightBarButtonItem = nil;
	if(bOK){
		[self.table reloadData];
	}else {
		NSString *alTitle = [NSString stringWithString:(NSLocalizedStringFromTable(@"ERROR",@"main",@""))];
		NSString *alMessage = [NSString stringWithString:(NSLocalizedStringFromTable(@"UPLOAD_ERROR",@"main",@""))];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alTitle message:alMessage delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}

}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSInteger ret = 0;
	if(section == 0){
		if(imgs != nil){
			//if([imgs count] > 0){
				ret = [imgs count];
			//}
		}
	}
    return ret;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
#ifndef __IPHONE_3_0
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
#else
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
#endif
    }
    
    // Set up the cell...
	NSString *ctitle = nil;
	
	// TODO 设置 cell 的 a
	cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	
	NSInteger section = indexPath.section;
	NSInteger row = indexPath.row;
	if(section == 0){
		if(imgs != nil){
			id d = [imgs objectAtIndex:row];
			if([d isKindOfClass:[UploadItem class]]){
				UploadItem *uitem = d;
				ctitle = uitem.title;
				if(uitem.uploadState == US_UPLOADED){
					cell.accessoryType = UITableViewCellAccessoryCheckmark;
				}
			}
		}
	}
#ifndef __IPHONE_3_0
	cell.text = ctitle;
#else
    cell.textLabel.text = ctitle;
#endif
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	//UIViewController *about = [[ViewControllerChooser sharedChooser] choose:VCC_ID_ABOUT];
//	[self.navigationController pushViewController:about animated:YES];
	ItemEditViewController *editViewController = (ItemEditViewController *)[[ViewControllerChooser sharedChooser] choose:VCC_ID_EDIT];
	editViewController.editItem = [imgs objectAtIndex:indexPath.row];
	editViewController.uvc = self;
	// TODO 调试这个地方是否正常
	[editViewController.tableView reloadData];
	[self.navigationController pushViewController:editViewController animated:YES];
}



// Override to support conditional editing of the table view.
/**
 * 检查哪些可以编辑
 */
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
	NSInteger section = indexPath.section;
	BOOL ret = NO;
	if(section == 0){
		ret = YES;
	}
    return ret;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        //[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
		NSInteger row = indexPath.row;
		if(imgs != nil){
			NSInteger cc = [imgs count];
			if(row < cc){
				// TODO 表格的删除要确保数据更新
				[imgs removeObjectAtIndex:row];
				[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
			}
		}
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
    [super dealloc];
}


@end

